package com.moody.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.lang.reflect.Array;      
import java.lang.reflect.Constructor;      
import java.lang.reflect.Field;      
import java.lang.reflect.Method; 

public class SortUtil {

	private static SortUtil sortUtil = new SortUtil();
	private SortUtil(){
		
	}
	
	
	/**
	 * 
	 * @param list 待排序列表
	 * @param varName 根据对象某个属性进行排序
	 * @param order 1-升序 2-降序
	 * @return
	 */
	public static List sortByDate(List list, String fieldName, int order){
		Node nodeList = sortUtil.new Node();
		List<Object> resultList = new LinkedList<Object>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;

		if(order != 0 && order != 1) return list;
		for(Object o:list){
			String property2;
//			try {
				Object propertyObj = null;
				try {
					propertyObj = getProperty(o,fieldName);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(propertyObj != null){
					try {
						date = sdf.parse(propertyObj.toString());
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					property2 = sdf.format(date);
				}
				else{
					property2 = "0";
				}
				Node node = sortUtil.new Node(o,property2);
				if(nodeList.next == null)nodeList.next = node;
				else{
					Node pre = nodeList;
					Node current = nodeList.next;
					while(current != null){
						if(order == 1){//升序
							if(current.var.compareTo(property2) > 0){
								pre.next = node;
								node.next = current;
								break;
							}
							else{
								pre = current;
								current = current.next;
							}
						}
						else if (order == 0){//降序
							if(current.var.compareTo(property2) < 0){
								pre.next = node;
								node.next = current;
								break;
							}
							else{
								pre = current;
								current = current.next;
							}
						}
					}
					if(current == null){
						pre.next = node;
					}
				}
//			} 
			
			
		}
		Node current = nodeList.next;
		while(current != null){
			resultList.add(current.o);
			current = current.next;
		}
		if(resultList != null) return resultList;
		else return list;
		
	}
	
	 @SuppressWarnings({ "unchecked" })
	public static Object getProperty(Object owner, String fieldName) throws Exception {      
	        Class ownerClass = owner.getClass();
	        Field field;
	        Object property = null;
			field = ownerClass.getDeclaredField(fieldName);
			field.setAccessible(true);
			property = field.get(owner); 
			return property;
	    }
	
	public class Node{
		Object o;
		String var;
		Node next;
		
		Node(){
			
		}
		
		Node(Object o, String var){
			this.o = o;
			this.var = var;
		}
	}

}
